@extends('layouts.app')

@section('title', '添加定时记账')

@push('styles')
<style>
    .account-books-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 20px;
        text-align: center;
        position: relative;
    }

    .account-books-title {
        font-size: 20px;
        font-weight: 600;
        margin: 0;
    }

    .app-container {
        padding-bottom: 0;
    }
    .page-container {
        min-height: 100vh;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    .page-header {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        height: 44px;
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        display: flex;
        align-items: center;
        padding: 0 20px;
        z-index: 100;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    }

    .page-title {
        flex: 1;
        text-align: center;
        font-size: 20px;
        font-weight: 700;
        margin: 0;
        background: linear-gradient(135deg, #667eea, #764ba2);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }

    .content-container {
        padding-top: 64px;
        padding-bottom: 80px;
        padding-left: 20px;
        padding-right: 20px;
    }

    .form-container {
        margin-bottom: 30px;
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.2);
    }

    .form-group {
        margin-bottom: 25px;
    }

    .form-label {
        display: block;
        margin-bottom: 10px;
        font-size: 15px;
        color: #4a5568;
        font-weight: 600;
    }

    .form-control {
        width: 100%;
        height: 44px;
        padding: 0 15px;
        border: 2px solid #e2e8f0;
        border-radius: 12px;
        font-size: 16px;
        box-sizing: border-box;
        transition: all 0.3s ease;
        background: #f8f9fa;
    }

    .form-control:focus {
        outline: none;
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        background: white;
        transform: translateY(-1px);
    }

    textarea.form-control {
        height: auto;
        padding: 15px;
    }

    .period-container {
        margin-bottom: 25px;
    }

    .period-title {
        font-size: 16px;
        color: #4a5568;
        margin-bottom: 15px;
        font-weight: 600;
    }

    .period-tabs {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
    }

    .period-tab {
        flex: 1;
        min-width: 80px;
        text-align: center;
        padding: 12px 8px;
        font-size: 14px;
        color: #718096;
        background: #f8f9fa;
        border: 2px solid #e2e8f0;
        border-radius: 12px;
        cursor: pointer;
        transition: all 0.3s ease;
        font-weight: 600;
    }

    .period-tab:hover {
        border-color: #667eea;
        transform: translateY(-1px);
    }

    .period-tab.active {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-color: #667eea;
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    }

    .period-value-container {
        margin-top: 20px;
        display: none;
    }

    /* 响应式设计 */
    @media (max-width: 480px) {
        .category-list {
            grid-template-columns: repeat(3, 1fr);
        }

        .subcategory-list {
            grid-template-columns: repeat(3, 1fr);
        }

        .period-tabs {
            grid-template-columns: repeat(4, 1fr);
            display: grid;
        }
    }

    /* 年度执行日期选择器样式 */
    .year-date-selector {
        display: flex;
        gap: 10px;
    }

    .year-date-selector select {
        flex: 1;
    }

    /* 其他样式保持不变 */

    /* 年度执行日期选择器样式 */
    .year-date-selector {
        display: flex;
        gap: 10px;
    }

    .year-date-selector select {
        flex: 1;
    }

    /* 确保所有周期值容器初始隐藏 */
    .period-value-container {
        margin-top: 20px;
        display: none;
    }

    /* 初始化时隐藏年度选择器 */
    #periodYearContainer {
        display: none;
    }
</style>
@endpush

@section('content')
<div class="account-books-header">
    <button class="back-btn" onclick="window.location.href = '{{ route('auto-transaction.index') }}'">‹</button>
    <h1 class="account-books-title">添加定时记账</h1>
</div>

<div class="form-container">
    <form id="autoRecordForm">
        @csrf

        <!-- 记账名称 -->
        <div class="form-group">
            <label for="title" class="form-label">记账名称</label>
            <input type="text" id="title" name="title" class="form-control" placeholder="请输入记账名称" required>
        </div>

        <!-- 收支类型 -->
        <div class="record-type-tabs">
            <div class="record-type-tab expense active" id="expense-tab" data-type="expense">支出</div>
            <div class="record-type-tab income" id="income-tab" data-type="income">收入</div>
        </div>
        <input type="hidden" id="transaction-type" name="type" value="{{ $type }}">

        <!-- 金额 -->
        <div class="form-group">
            <label class="form-label">金额</label>
            <input type="number" class="form-input" id="amount" name="amount" placeholder="0.00" step="0.01" value="" required>
        </div>

        <div class="form-group">
            <label class="form-label">分类</label>

            <!-- 支出分类 -->
            <div class="category-selector" id="expense-categories" style="{{ $type === 'expense' ? 'display: grid' : 'display: none' }}">
                @if(count($expenseCategories) > 0)
                    @foreach($expenseCategories as $index => $cat)
                        <div class="category-item {{ $index === 0 && $type === 'expense' ? 'active' : '' }}" data-category="{{ $cat->name }}" data-category-id="{{ $cat->id }}" data-type="expense">
                            <div class="category-icon">{{ $cat->icon }}</div>
                            <div class="category-name">{{ $cat->name }}</div>
                        </div>
                    @endforeach
                @else
                    <div style="grid-column: 1 / -1; text-align: center; color: #999;">暂无支出分类</div>
                @endif
            </div>

            <!-- 收入分类 -->
            <div class="category-selector" id="income-categories" style="{{ $type === 'income' ? 'display: grid' : 'display: none' }}">
                @if(count($incomeCategories) > 0)
                    @foreach($incomeCategories as $index => $cat)
                        <div class="category-item {{ $index === 0 && $type === 'income' ? 'active' : '' }}" data-category="{{ $cat->name }}" data-category-id="{{ $cat->id }}" data-type="income">
                            <div class="category-icon">{{ $cat->icon }}</div>
                            <div class="category-name">{{ $cat->name }}</div>
                        </div>
                    @endforeach
                @else
                    <div style="grid-column: 1 / -1; text-align: center; color: #999;">暂无收入分类</div>
                @endif
            </div>

            <!-- 支出二级分类 -->
            @foreach($expenseCategories as $cat)
                @if($cat->subCategories->count() > 0)
                    <div class="subcategory-selector" id="subcategory-expense-{{ $cat->id }}" style="display: none">
                        <div class="subcategory-title">{{ $cat->name }} - 二级分类</div>
                        <div class="subcategory-box">
                            @foreach($cat->subCategories as $subCat)
                                <div class="subcategory-item" data-subcategory="{{ $subCat->name }}" data-subcategory-id="{{ $subCat->id }}">
                                    <div class="subcategory-icon">{{ $subCat->icon }}</div>
                                    <div class="subcategory-name">{{ $subCat->name }}</div>
                                </div>
                            @endforeach
                        </div>
                    </div>
                @endif
            @endforeach

            <!-- 收入二级分类 -->
            @foreach($incomeCategories as $cat)
                @if($cat->subCategories->count() > 0)
                    <div class="subcategory-selector" id="subcategory-income-{{ $cat->id }}" style="display: none">
                        <div class="subcategory-title">{{ $cat->name }} - 二级分类</div>
                        <div class="subcategory-box">
                            @foreach($cat->subCategories as $subCat)
                                <div class="subcategory-item" data-subcategory="{{ $subCat->name }}" data-subcategory-id="{{ $subCat->id }}">
                                    <div class="subcategory-icon">{{ $subCat->icon }}</div>
                                    <div class="subcategory-name">{{ $subCat->name }}</div>
                                </div>
                            @endforeach
                        </div>
                    </div>
                @endif
            @endforeach

            <div class="category-selected-info" id="category-selected-info"></div>
        </div>

        <!-- 执行频率 -->
        <div class="period-container">
            <div class="period-title">执行频率</div>
            <div class="period-tabs">
                <button type="button" class="period-tab active" data-value="1">每天</button>
                <button type="button" class="period-tab" data-value="2">每周</button>
                <button type="button" class="period-tab" data-value="3">每月</button>
                <button type="button" class="period-tab" data-value="4">每年</button>
            </div>
            <input type="hidden" id="periodType" name="period_type" value="1">

            <!-- 周期值（每周几/每月几号） -->
            <div class="period-value-container" id="periodWeekContainer">
                <label for="periodWeekValue" class="form-label">每周几执行</label>
                <select id="periodWeekValue" class="form-control">
                    <option value="0">周日</option>
                    <option value="1" selected>周一</option>
                    <option value="2">周二</option>
                    <option value="3">周三</option>
                    <option value="4">周四</option>
                    <option value="5">周五</option>
                    <option value="6">周六</option>
                </select>
            </div>

            <div class="period-value-container" id="periodMonthContainer">
                <label for="periodMonthValue" class="form-label">每月几号执行</label>
                <select id="periodMonthValue" class="form-control">
                    @for($i = 1; $i <= 31; $i++)
                    <option value="{{ $i }}">{{ $i }}日</option>
                    @endfor
                </select>
            </div>

            <div class="period-value-container" id="periodYearContainer">
                <label for="periodYearMonth" class="form-label">每年几月几日执行</label>
                <div class="year-date-selector">
                    <select id="periodYearMonth" class="form-control">
                        @for($i = 1; $i <= 12; $i++)
                        <option value="{{ $i }}">{{ $i }}月</option>
                        @endfor
                    </select>
                    <select id="periodYearDay" class="form-control">
                        @for($i = 1; $i <= 31; $i++)
                        <option value="{{ $i }}">{{ $i }}日</option>
                        @endfor
                    </select>
                </div>
            </div>

            <input type="hidden" id="periodValue" name="period_value" value="">
        </div>

        <!-- 执行时间 -->
        <div class="form-group">
            <label for="executeTime" class="form-label">执行时间</label>
            <input type="time" id="executeTime" name="execute_time" class="form-control" value="09:00" required>
        </div>

        <!-- 开始日期 -->
        <div class="form-group">
            <label for="startDate" class="form-label">开始日期</label>
            <input type="date" id="startDate" name="start_date" class="form-control" required>
        </div>

        <!-- 结束日期 -->
        <div class="form-group">
            <label for="endDate" class="form-label">结束日期 (可选)</label>
            <input type="date" id="endDate" name="end_date" class="form-control">
        </div>

        <!-- 备注 -->
        <div class="form-group">
            <label for="description" class="form-label">备注 (可选)</label>
            <textarea id="description" name="description" class="form-control" rows="3" placeholder="添加备注..."></textarea>
        </div>
    </form>
</div>

<div class="bottom-bar">
    <button type="button" class="cancel-btn" id="cancelBtn">取消</button>
    <button type="button" class="save-btn" id="saveBtn">保存</button>
</div>
@endsection

@push('scripts')
<script>
    $(document).ready(function() {
        // 初始化日期
        const today = new Date();
        const formattedDate = today.toISOString().split('T')[0];
        $('#startDate').val(formattedDate);

        let selectedCategoryId = null;
        let selectedSubCategoryId = null;
        let selectedCategoryId_ori = selectedCategoryId;
        let selectedSubCategoryId_ori = selectedSubCategoryId;

        // 切换收入支出标签
        const expenseTab = $('#expense-tab');
        const incomeTab = $('#income-tab');
        const expenseCategories = $('#expense-categories');
        const incomeCategories = $('#income-categories');

        function switchToExpense() {
            console.log('切换到支出');
            expenseTab.addClass('active');
            incomeTab.removeClass('active');
            expenseCategories.show();
            incomeCategories.hide();
            $('#transaction-type').val('expense');
            $('#record-form-title').text('记录支出');
            hideAllSubcategories();

            // 选中第一个支出分类
            const firstExpenseCategory = expenseCategories.find('.category-item').first();
            if (firstExpenseCategory.length) {
                expenseCategories.find('.category-item').removeClass('active');
                firstExpenseCategory.addClass('active');
                selectedCategoryId = firstExpenseCategory.data('category-id');
                selectedSubCategoryId = null;

                // 显示对应的二级分类
                selectSubCategoryAuto('expense', 0)
            }
        }

        function switchToIncome() {
            incomeTab.addClass('active');
            expenseTab.removeClass('active');
            incomeCategories.show();
            expenseCategories.hide();
            $('#transaction-type').val('income');
            $('#record-form-title').text('记录收入');
            hideAllSubcategories();

            // 选中第一个收入分类
            const firstIncomeCategory = incomeCategories.find('.category-item').first();
            if (firstIncomeCategory.length) {
                incomeCategories.find('.category-item').removeClass('active');
                firstIncomeCategory.addClass('active');
                selectedCategoryId = firstIncomeCategory.data('category-id');
                selectedSubCategoryId = null;

                // 显示对应的二级分类
                selectSubCategoryAuto('income', 0)
            }
        }

        function selectSubCategoryAuto(type, sub_id = 0) {
            const subcategorySelector = $(`#subcategory-${type}-${selectedCategoryId}`);
            subcategorySelector.show();
            var firstSubCategory;
            if (! sub_id) {
                if (selectedSubCategoryId_ori && selectedCategoryId === selectedCategoryId_ori) sub_id = selectedSubCategoryId_ori;
            }
            if (sub_id) {
                firstSubCategory = subcategorySelector.find(`.subcategory-item[data-subcategory-id="${sub_id}"]`)
            }
            if (!firstSubCategory || !firstSubCategory.length) {
                firstSubCategory = subcategorySelector.find('.subcategory-item').first();
            }

            if (firstSubCategory.length) {
                firstSubCategory.addClass('active');
                selectedSubCategoryId = firstSubCategory.data('subcategory-id');
                showSelectInfo()
            }
        }

        function showSelectInfo() {
            // 更新已选分类信息
            const categoryName = $('.category-item.active').data('category');
            const subcategoryName = $('.subcategory-item.active').data('subcategory');
            $('#category-selected-info').text(`已选: ${categoryName} - ${subcategoryName}`).show();
        }

        expenseTab.click(switchToExpense);
        incomeTab.click(switchToIncome);

        // 隐藏所有二级分类
        function hideAllSubcategories() {
            $('.subcategory-selector').hide();
            $('.subcategory-item').removeClass('active');
            $('#category-selected-info').hide();
        }

        // 一级分类选择
        $('.category-item').click(function() {
            const parent = $(this).parent();
            parent.find('.category-item').removeClass('active');
            $(this).addClass('active');

            selectedCategoryId = $(this).data('category-id');
            selectedSubCategoryId = null;

            hideAllSubcategories();

            // 显示对应的二级分类
            selectSubCategoryAuto($(this).data('type'), selectedSubCategoryId)
        });

        // 二级分类选择
        $('.subcategory-item').click(function() {
            const parent = $(this).parent();
            parent.find('.subcategory-item').removeClass('active');
            $(this).addClass('active');

            selectedSubCategoryId = $(this).data('subcategory-id');

            // 更新已选分类信息
            showSelectInfo()
        });

        // 初始化默认选择
        const initialType = $('#transaction-type').val();
        if (initialType === 'expense') {
            const firstExpenseCategory = expenseCategories.find('.category-item').first();
            if (firstExpenseCategory.length) {
                selectedCategoryId = firstExpenseCategory.data('category-id');
                expenseCategories.find('.category-item').removeClass('active');
                firstExpenseCategory.addClass('active');
                selectSubCategoryAuto('expense', selectedSubCategoryId)
            }
        } else {
            const firstIncomeCategory = incomeCategories.find('.category-item').first();
            if (firstIncomeCategory.length) {
                selectedCategoryId = firstIncomeCategory.data('category-id');
                incomeCategories.find('.category-item').removeClass('active');
                firstIncomeCategory.addClass('active');
                selectSubCategoryAuto('income', selectedSubCategoryId)
            }
        }

        // 执行频率选择
        $('.period-tab').click(function() {
            const periodType = $(this).data('value');

            // 更新样式
            $('.period-tab').removeClass('active');
            $(this).addClass('active');

            // 更新周期类型
            $('#periodType').val(periodType);

            // 显示/隐藏对应的周期值选择
            $('.period-value-container').hide();
            $('#periodValue').val('');

            if (periodType === 2) { // 每周
                $('#periodWeekContainer').show();
                $('#periodValue').val($('#periodWeekValue').val());
            } else if (periodType === 3) { // 每月
                $('#periodMonthContainer').show();
                $('#periodValue').val($('#periodMonthValue').val());
            } else if (periodType === 4) { // 每年
                $('#periodYearContainer').show();
                updateYearlyPeriodValue();
            }
        });

        // 周期值变化
        $('#periodWeekValue').change(function() {
            $('#periodValue').val($(this).val());
        });

        $('#periodMonthValue').change(function() {
            $('#periodValue').val($(this).val());
        });

        // 年度周期值变化
        $('#periodYearMonth, #periodYearDay').change(function() {
            updateYearlyPeriodValue();
        });

        // 更新年度周期值
        function updateYearlyPeriodValue() {
            const month = parseInt($('#periodYearMonth').val());
            const day = parseInt($('#periodYearDay').val());
            // 格式：月份*100+日期，例如：315表示3月15日
            const yearValue = month * 100 + day;
            $('#periodValue').val(yearValue);
        }

        // 取消按钮
        $('#cancelBtn').click(function() {
            window.location.href = '{{ route("auto-transaction.index", ["book_id" => $book->id]) }}';
        });

        // 保存按钮
        $('#saveBtn').click(function() {
            // 表单验证
            if (!validateForm()) {
                return;
            }

            // 准备表单数据
            const formData = {
                title: $('#title').val(),
                type: $('#transaction-type').val(),
                amount: $('#amount').val(),
                category_id: selectedCategoryId,
                sub_category_id: selectedSubCategoryId,
                period_type: $('#periodType').val(),
                period_value: $('#periodValue').val() || null,
                execute_time: $('#executeTime').val(),
                start_date: $('#startDate').val(),
                end_date: $('#endDate').val() || null,
                description: $('#description').val(),
                book_id: '{{ $book->id }}',
                _token: $('input[name="_token"]').val()
            };

            // 发送请求
            $.ajax({
                url: '{{ route("auto-transaction.store") }}',
                type: 'POST',
                data: formData,
                success: function(response) {
                    if (response.success) {
                        window.location.href = '{{ route("auto-transaction.index", ["book_id" => $book->id]) }}';
                    } else {
                        alert(response.message || '保存失败');
                    }
                },
                error: function(xhr) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON.errors;
                        const errorMessages = [];

                        for (const key in errors) {
                            errorMessages.push(errors[key][0]);
                        }

                        alert('表单验证失败：\n' + errorMessages.join('\n'));
                    } else {
                        showError(xhr.responseJSON.message || '保存失败，请稍后重试', xhr.responseJSON);
                    }

                    console.error(xhr);
                }
            });
        });

        // 表单验证
        function validateForm() {
            // 验证标题
            if (!$('#title').val()) {
                alert('请输入记账名称');
                $('#title').focus();
                return false;
            }

            // 验证金额
            const amount = parseFloat($('#amount').val());
            if (isNaN(amount) || amount <= 0) {
                alert('请输入有效金额');
                $('#amount').focus();
                return false;
            }

            // 验证分类
            if (!selectedSubCategoryId || !selectedCategoryId) {
                alert('请选择分类');
                return false;
            }

            // 验证开始日期
            if (!$('#startDate').val()) {
                alert('请选择开始日期');
                $('#startDate').focus();
                return false;
            }

            // 验证结束日期
            const startDate = new Date($('#startDate').val());
            const endDate = $('#endDate').val() ? new Date($('#endDate').val()) : null;

            if (endDate && endDate < startDate) {
                alert('结束日期不能早于开始日期');
                $('#endDate').focus();
                return false;
            }

            return true;
        }

        // 自动选中第一个分类
        $('#expenseCategories .category-item:first').click();

        // 初始化周期值
        // 默认选择每周，初始化周期值
        const initialPeriodType = parseInt($('#periodType').val());
        if (initialPeriodType === 2) {
            $('#periodValue').val($('#periodWeekValue').val());
        } else if (initialPeriodType === 3) {
            $('#periodValue').val($('#periodMonthValue').val());
        } else if (initialPeriodType === 4) {
            updateYearlyPeriodValue();
        } else {
            $('#periodValue').val('');
        }

        // 如果URL中有参数，自动选择对应的分类
        const urlParams = new URLSearchParams(window.location.search);
        const categoryParam = urlParams.get('category');
        const typeParam = urlParams.get('type') || 'expense';

        if (typeParam === 'income') {
            $('#incomeTab').click();
        }

        if (categoryParam) {
            const $category = $(`.category-item[data-id="${categoryParam}"][data-type="${typeParam}"]`);
            if ($category.length) {
                $category.click();
            }
        }
    });
</script>
@endpush
